package com.scholarship.modules.login.service.impl;

import com.scholarship.common.utils.RedisUtil;
import com.scholarship.modules.admin.mapper.AUserInfoMapper;
import com.scholarship.modules.login.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.Future;

/**
 * @Author Z.J.H
 * @create 2021/7/27 16:12
 */
@Slf4j
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Autowired
    private AUserInfoMapper aUserInfoMapper;

    @Autowired
    private RedisUtil redisUtil;

    //邮件发件人
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮件
     * @param to    收信邮件
     */
    @Async(value = "asyncExecutor")
    @Override
    public Future<Boolean> sendMail(String to) throws Exception {

        String baseEmail = Base64.getEncoder().encodeToString(to.getBytes("utf-8"));
        if(aUserInfoMapper.getEmailIsExist(baseEmail) == 0) {
            //throw new EmailException("该邮箱未绑定学号");
            return new AsyncResult<>(false);
        }

        //6位验证码
        String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
        String text = "尊敬的用户,您好:\n"
                + "\n本次请求的邮件验证码为:" + checkCode + ",本验证码5分钟内有效，请及时输入。（请勿泄露此验证码）\n"
                + "\n如非本人操作，请忽略该邮件。\n(这是一封自动发送的邮件，请不要直接回复）";
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject("奖学金管理系统");
        message.setText(text);

        try {
            mailSender.send(message);
            //用redis进行存储验证码，时效5分钟
            redisUtil.set(baseEmail,checkCode,300L);
            return new AsyncResult<>(true);
        }catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new Exception("发送失败，请联系客服");
        }
    }

    /**
     * 比对验证码
     * @param email
     * @param code
     * @return
     */
    @Override
    public Boolean compareCode(String email, String code) throws Exception {
        String baseEmail = Base64.getEncoder().encodeToString(email.getBytes("utf-8"));
        String checkCode = redisUtil.get(baseEmail);
        if(StringUtils.isEmpty(checkCode)) {
            throw new Exception("验证码过期");
        }
        if(!code.equals(checkCode)) {
            return false;
        }
        redisUtil.remove(baseEmail);
        return true;
    }
}
